const express = require('nanoexpress')
const Route = require('nanoexpress/cjs/Route.js');
const staticServe = require('@nanoexpress/middleware-static-serve/cjs');
const { createPageRender } = require('vite-plugin-ssr')
const path = require('path')

const isProduction = process.env.NODE_ENV === 'production'
const root = `${__dirname}/..`

startServer()

async function startServer() {
  const app = express()
  const route = new Route()
  app.use(route)
  route.get('/hello', async (req, res) => {
    res.send('hello')
  })
  let viteDevServer
  if (isProduction) {
    const static = `${root}/dist/client`
    console.log('static', static)
    app.use(staticServe(static, {
      mode: 'cached',
      compressed: false
    }));
  } else {
    const vite = require('vite')
    viteDevServer = await vite.createServer({
      root,
      server: { middlewareMode: true }
    })
    app.use(viteDevServer.middlewares)
  }


  const renderPage = createPageRender({ viteDevServer, isProduction, root })
  app.get('/*', async (req, res, next) => {
    const url = req.url
    const pageContext = {
      url
    }
    const result = await renderPage(pageContext)
    if (result.nothingRendered) return next()
    res.status(result.statusCode).send(result.renderResult)
  })

  const port = process.env.PORT || 3000
  app.listen(port)
  console.log(`Server running at http://localhost:${port}`)
}
